const accessTokenService = require('services/accessToken')
const request = require('request-promise')
const moment = require('moment')
const orderService = require('services/order')
const houseService = require('services/house')
const ORDER_TEMPLATE_ID = 'Kcy6h6SSSC2Odo73FmTqESCEgSGfAIpMTjbdFUk1KI0'

const getList = async () => {
  const token = await accessTokenService.get()
  const result = await request.get({json:true, uri:`https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list?access_token=${token}`})
  return result.list
}

const sendOrderSuccess = async (openId, orderId, data) => {
  const token = await accessTokenService.get()
  const order = await orderService.get(orderId)
  const house = await houseService.get(order.houseId)
  
  const prepayId = order.prepayId
  
  let templateData = {
    touser: openId,
    template_id: ORDER_TEMPLATE_ID,
    form_id: prepayId,
    page: '/pages/order/detail?orderId=' + orderId,
    data: {
      "keyword1": {
        "value": house.address // 地址
      },
      "keyword2": {
        "value": moment(order.startTime).format('YYYY-MM-DD HH:mm') // 时间
      }, 
      "keyword3": {
        "value": "¥" + order.orderPrice // 购买金额
      },
      "keyword4": {
        "value": "40012345678" // 售后客服
      }
    }
  }

  const result = await request({
    method: 'POST',
    json: true,
    uri: `https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=${token}`,
    body: templateData
  })
}

module.exports = {
  getList,
  sendOrderSuccess
}
